<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\CreateUserRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class TestController extends Controller
{
    public function __construct()
	{
		$this->middleware(['jwt.auth','jwt.refresh'])->except(['authenticate']);
	}

	public function authenticate(CreateUserRequest $request)
	{
		// grab credentials from the request
		$credentials = $request->only('email', 'password');

		try {
			// attempt to verify the credentials and create a token for the user
			if (! $token = JWTAuth::attempt($credentials)) {
				return response()->json(['error' => 'invalid_credentials'], 401);
			}
		} catch (JWTException $e) {
			// something went wrong whilst attempting to encode the token
			return response()->json(['error' => 'could_not_create_token'], 500);
		}

		// all good so return the token
		return response()->json(compact('token'));
	}
}
